<template>
  <van-sticky :offset-top="10">
    <van-cell-group inset>
      <van-field v-model="todoText" center rows="1" placeholder="添加任务">
        <template #button>
          <van-button size="small" color="#FC5833" @click="addTask">添加</van-button>
        </template>
      </van-field>
    </van-cell-group>
  </van-sticky>

  <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="loadToDoList">
    <van-swipe-cell v-for="todo in todoList" :key="todo.id">
      <template #left>
        <van-button v-if="todo.status === 0" square type="primary" color="#19AA4A" text="完成" @click="finishToDo(todo.id)" />
      </template>
      <van-cell v-if="todo.status === 0" :border="false" v-model:value="todo.text"/>
      <template #right>
        <van-button v-if="todo.status === 0" square color="#FFC806" text="编辑" @click="showEditToDoDialog(todo.id)" />
        <van-button v-if="todo.status === 0" square type="primary" text="详情" @click="showDetailToDoWindow(todo.id)" />
      </template>
    </van-swipe-cell>
  </van-list>

  <van-dialog v-model:show="showDialog"
              show-cancel-button
              confirm-button-text="修改"
              @confirm="editTodo"
              @cancel="cancelEditTodo">
    <van-field v-model="todoInfo.text" placeholder="todo" />
    <van-cell title="TODO完成期限" v-if="todoInfo.beginTime && todoInfo.endTime"
              :value="todoInfo.beginTime.substring(5)
              + ' - '
              + todoInfo.endTime.substring(5)"
              @click="showCalendar = true" />
  </van-dialog>
  <van-calendar v-model:show="showCalendar" type="range" @confirm="onConfirm" />

  <van-action-sheet v-model:show="showDetailWindow" title="详情">
    <van-space direction="vertical" fill >
      <div style="height: 20px; margin: 10px auto auto 20px">
        <span class="title_class">创建日期</span>
        <span class="contend_class">{{todoInfo.createTime}}</span>
      </div>
      <div style="height: 20px; margin: 10px auto auto 20px">
        <span class="title_class">倒计时</span>
        <span class="contend_class">
          <van-count-down
              :time="(new Date(todoInfo.endTime).getTime() - new Date(todoInfo.beginTime).getTime())"
              format="DD 天 HH 时 mm 分 ss 秒" />
        </span>
      </div>
      <van-divider :style="{ color: '#FF841C', borderColor: '#FF841C'}" dashed content-position="left">
        TODO详情
      </van-divider>
      <div style="height: 100px; margin: auto auto auto 20px">
        <span class="contend_class" style="font-size: small">{{todoInfo.text}}</span>
      </div>
    </van-space>
  </van-action-sheet>
</template>

<script setup>
import {ref} from "vue";
import {addToDo, editToDoReq, finishToDoReq, getToDoList} from "@/api/todo";
import {Notify} from "vant";

  // 添加任务文本
  let todoText = ref('');
  // todo列表
  const todoList = ref([]);
  const loading = ref(false);
  const finished = ref(false);
  //////某个todo的详细信息，供修改和获取详细信息使用////
  const todoInfo = ref({});
  // dialog修改窗口
  const showDialog = ref(false);
  let editTodoInfo = {};
  // actionSheet详情窗口
  const showDetailWindow = ref(false);
  // 日历参数
  let showCalendar = ref(false);

  // 日历相关方法
  const formatDate = (date) => `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
  const onConfirm = (values) => {
    const [start, end] = values;
    console.log(start)
    console.log(end)
    showCalendar.value = false;
    todoInfo.value.endTime = formatDate(end);
    todoInfo.value.beginTime = formatDate(start);
    console.log(`${formatDate(start)} - ${formatDate(end)}`)
  };

  // 新增task
  const addTask = () => {
    console.log(todoText.value)
    // 新增todo请求
    addToDo(todoText.value).then(res => {
      if (res.code === 20000) {
        todoList.value.unshift(res.data);
      } else {
        Notify({ type: 'warning', message: res.description});
      }
    }).catch(res => {
      console.log(res.message)
    });
    todoText.value = ''
  }

  // 加载（获取）todo数据
  const loadToDoList = () => {
    // 获取todo列表
    getToDoList().then(res => {
      if (res.code === 20000) {
        todoList.value = res.data;
        loading.value = false;
        finished.value = true;
      } else {
        Notify({ type: 'warning', message: res.description});
      }
    }).catch(res => {
      console.log(res.message)
    });
  };

  // 完成todo
  const finishToDo = (id) => {
    console.log(id)
    // 完成todo请求
    finishToDoReq(id).then(res => {
      if (res.code === 20000) {
        Notify({ type: 'success', message: '已完成'});
        for (let i = 0; i < todoList.value.length; i++) {
          if (todoList.value[i].id === id) {
            todoList.value.splice(i, 1)
          }
        }
      } else {
        Notify({ type: 'warning', message: res.description});
      }
    }).catch(res => {
      console.log(res.message)
    });
  }

  // 获取todo信息
  const getDetailToDoInfo = (id) => {
    console.log(id)
    for (let i = 0; i < todoList.value.length; i++) {
      if (todoList.value[i].id === id) {
        return todoList.value[i];
      }
    }
  };

  // 显示编辑todo对话框
  const showEditToDoDialog = (id) => {
    todoInfo.value = getDetailToDoInfo(id);
    editTodoInfo.id = todoInfo.value.id;
    editTodoInfo.text = todoInfo.value.text;
    editTodoInfo.endTime = todoInfo.value.endTime;
    editTodoInfo.beginTime = todoInfo.value.beginTime;
    console.log(todoInfo.value)
    console.log(editTodoInfo)
    showDialog.value = true;
  }

  // 编辑todo
  const editTodo = () => {
    if (!todoInfo.value) {
      console.log('edit error')
    }
    // 发送修改todo请求，参数为todoInfo
    editToDoReq(todoInfo.value).then(res => {
      if (res.code === 20000) {
        Notify({ type: 'success', message: res.data});
      } else {
        Notify({ type: 'warning', message: res.description});
        cancelEditTodo();
      }
    }).catch(res => {
      console.log(res.message)
      cancelEditTodo();
    });
    console.log(todoInfo.value)
  };

  // 取消编辑
  const cancelEditTodo = () => {
    console.log(editTodoInfo)
    todoInfo.value.text = editTodoInfo.text;
    todoInfo.value.endTime = editTodoInfo.endTime;
    todoInfo.value.beginTime = editTodoInfo.beginTime;
  };

  // 展示详情窗口
  const showDetailToDoWindow = (id) => {
    todoInfo.value = getDetailToDoInfo(id);
    console.log(todoInfo.value)
    showDetailWindow.value = true;
  }


</script>

<style scoped>
.title_class {
  font-size: large;
  font-weight: bold;
  margin-right: 17px;
}
.contend_class {
  font-size: medium;
  color: #93939b;
}
</style>
